import os
import requests
import hashlib
from pathlib import Path
from typing import Optional
import logging

class IconManager:
    """图标管理器 - 本地优先，不存在时下载并缓存"""
    
    def __init__(self, static_dir: str = "static", images_dir: str = "images"):
        self.static_dir = Path(static_dir)
        self.images_dir = self.static_dir / images_dir
        self.images_dir.mkdir(parents=True, exist_ok=True)
        
    def get_icon_path(self, stock_code: str, remote_url: Optional[str] = None) -> str:
        """
        获取图标路径，优先使用本地，不存在时下载并缓存
        
        Args:
            stock_code: 股票代码
            remote_url: 远程图标URL（可选）
            
        Returns:
            图标URL路径
        """
        # 本地图标文件路径
        local_file = self.images_dir / f"{stock_code}.gif"
        
        # 如果本地存在，直接返回
        if local_file.exists():
            return f"/static/images/{stock_code}.gif"
        
        # 如果提供了远程URL，尝试下载
        if remote_url:
            try:
                self._download_icon(stock_code, remote_url)
                return f"/static/images/{stock_code}.gif"
            except Exception as e:
                logging.warning(f"下载图标失败 {stock_code}: {e}")
        
        # 返回默认图标或空字符串
        return ""
    
    def _download_icon(self, stock_code: str, remote_url: str) -> bool:
        """
        下载并缓存图标
        
        Args:
            stock_code: 股票代码
            remote_url: 远程图标URL
            
        Returns:
            是否下载成功
        """
        try:
            # 发送请求下载图片
            response = requests.get(remote_url, timeout=10, stream=True)
            response.raise_for_status()
            
            # 检查内容类型
            content_type = response.headers.get('content-type', '').lower()
            if not content_type.startswith('image/'):
                raise ValueError(f"不是图片类型: {content_type}")
            
            # 保存到本地
            local_file = self.images_dir / f"{stock_code}.gif"
            with open(local_file, 'wb') as f:
                for chunk in response.iter_content(chunk_size=8192):
                    f.write(chunk)
            
            logging.info(f"图标下载成功: {stock_code}")
            return True
            
        except Exception as e:
            logging.error(f"下载图标失败 {stock_code}: {e}")
            return False
    
    def get_icon_url(self, stock_code: str, stock_image: Optional[str] = None) -> str:
        """
        获取图标URL，优先本地，其次远程下载
        
        Args:
            stock_code: 股票代码
            stock_image: 数据库中的图标URL
            
        Returns:
            图标URL
        """
        # 优先使用本地图标
        local_file = self.images_dir / f"{stock_code}.gif"
        if local_file.exists():
            return f"/static/images/{stock_code}.gif"
        
        # 如果有远程URL，尝试下载
        if stock_image and stock_image:
            return self.get_icon_path(stock_code, stock_image)
        
        # 返回空字符串（使用默认头像）
        return ""
    
    def batch_download_icons(self, icon_data: list) -> int:
        """
        批量下载图标
        
        Args:
            icon_data: 包含 stock_code 和 stock_image 的列表
            
        Returns:
            成功下载的数量
        """
        success_count = 0
        for item in icon_data:
            stock_code = item.get('stock_code')
            stock_image = item.get('stock_image')
            
            if stock_code and stock_image:
                if self._download_icon(stock_code, stock_image):
                    success_count += 1
        
        return success_count

# 全局实例
icon_manager = IconManager()
